<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoledialog = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolelist" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['vcenter', 'bdbot', i1 === 0 ? 'bdtop' : '']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightbgyId(scope.row, item1.id)">
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二 ，三级权限 -->
              <el-col :span="19">
                <!-- 渲染二级 -->
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightbgyId(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightbgyId(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="showeditRole(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-edit"
              @click="removeRoleById(scope.row.id)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-edit"
              @click="setright(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      :visible.sync="addRoledialog"
      width="30%"
      title="添加用户"
      @close="reSetForm"
    >
      <el-form
        :model="addRoleForm"
        :rules="addRoleFormrules"
        ref="addRoleForm"
        label-width="70px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoledialog = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户对话框 -->
    <el-dialog
      :visible.sync="editRoledialog"
      width="30%"
      title="编辑用户"
      @close="reSeteditForm"
    >
      <el-form
        :model="editRoleForm"
        :rules="editRoleFormrules"
        ref="editRoleForm"
        label-width="70px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoledialog = false">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setrightdialog"
      width="30%"
      @close="setrightdialogclosed"
    >
      <el-tree
        :data="rightlist"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defaultkeys"
        ref="treeref"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setrightdialog = false">取 消</el-button>
        <el-button type="primary" @click="allotright">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 所有角色列表数据
      rolelist: [],
      addRoledialog: false,
      editRoledialog: false,
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      addRoleFormrules: {},
      editRoleForm: {},
      editRoleFormrules: {},
      rightlist: [],
      setrightdialog: false,
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 获取已有权限的ID数组
      defaultkeys: [],
      roleID: ''
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.rolelist = res.data
      // console.log(this.rolelist)
    },
    addRole() {
      // 表单预验证
      this.$refs.addRoleForm.validate(async valid => {
        if (!valid) return
        // 发起添加用户请求
        const { data: res } = await this.$http.post('roles', this.addRoleForm)
        if (res.meta.status !== 201) return this.$message.error('添加用户失败')
        this.$message.success('添加用户成功')
        // close dialog
        this.adddialog = false
        // 刷新列表
        this.getRoleList()
      })
    },
    // 重置表单
    reSetForm() {
      this.$refs.addRoleForm.resetFields()
    },
    // 展示编辑对话框
    async showeditRole(id) {
      this.editRoledialog = true
      const { data: res } = await this.$http.get('roles/' + id)
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('查询用户失败')
      this.editRoleForm = res.data
      console.log(this.editRoleForm)
    },
    // 重置表单
    reSeteditForm() {
      this.$refs.editRoleForm.resetFields()
    },
    // 编辑修改角色
    editRole() {
      this.$refs.editRoleForm.validate(async valid => {
        if (!valid) return
        // 发起修改角色请求
        const { data: res } = await this.$http.put(
          'roles/' + this.editRoleForm.roleId,
          {
            roleName: this.editRoleForm.roleName,
            roleDesc: this.editRoleForm.roleDesc
          }
        )
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error('提交失败')
        // 刷新列表
        this.getRoleList()
        // 提示修改成功
        this.$message.success('修改用户信息成功')
        // close dialog
        this.editRoledialog = false
      })
    },
    // 删除角色
    async removeRoleById(id) {
      const reslut = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // console.log(typeof reslut)
      if (reslut !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('roles/' + id)

      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败！')
      }

      this.$message.success('删除用户成功！')
      this.getRoleList()
    },
    async removeRightbgyId(role, rightsid) {
      // console.log(role.children)
      const reslut = await this.$confirm(
        '此操作将永久删除该, 是权限否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // console.log(typeof reslut)
      if (reslut !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightsid}`
      )
      // console.log(res.data)
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败！')
      }

      this.$message.success('删除权限成功！')
      // this.getRoleList()
      role.children = res.data
    },
    async setright(role) {
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.rightlist = res.data
      this.getleafkeys(role, this.defaultkeys)
      this.setrightdialog = true
      this.roleID = role.id
    },
    getleafkeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getleafkeys(item, arr))
    },
    setrightdialogclosed() {
      this.defaultkeys = []
    },
    // 角色分配
    async allotright() {
      // 展开复制
      const keys = [
        ...this.$refs.treeref.getCheckedKeys(),
        ...this.$refs.treeref.getHalfCheckedKeys()
      ]
      const idstr = keys.join(',')
      // console.log(typeof keys)
      // console.log(typeof idstr)
      const { data: res } = await this.$http.post(
        `roles/${this.roleID}/rights`,
        {
          rids: idstr
        }
      )
      if (res.meta.status !== 200) return this.$message.error('分配失败')
      this.$message.success('分配成功')
      this.getRoleList()
      this.setrightdialog = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbot {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
